﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinServiceKeepAliveTest
{
    public class LogHelper : IDisposable
    {
        private string LogFile;

        private static StreamWriter sw;

        private string logIsWrite = ConfigurationManager.AppSettings["LogIsWrite"].ToString();

        public LogHelper()
        {
            CreateLoggerFile(null);
        }

        public LogHelper(string _log)
        {
            CreateLoggerFile(_log);
        }

        private void CreateLoggerFile(string fileName)
        {
            if (!(logIsWrite == "true"))
            {
                return;
            }

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = DateTime.Now.ToString("yyyyMMdd");
            }

            object obj = null;
            if (obj == null)
            {
                LogFile = ConfigurationManager.AppSettings["LogFilePath"].ToString();
                if (!Directory.Exists(LogFile))
                {
                    Directory.CreateDirectory(LogFile);
                }
            }
            else
            {
                LogFile = obj.ToString();
            }

            if (1 > LogFile.Length)
            {
                Console.WriteLine("配置文件中没有指定日志文件目录！");
                return;
            }

            if (!Directory.Exists(LogFile))
            {
                Console.WriteLine("配置文件中指定日志文件目录不存在！");
                return;
            }

            if (LogFile.Substring(LogFile.Length - 1, 1).Equals("/") || LogFile.Substring(LogFile.Length - 1, 1).Equals("\\"))
            {
                LogFile = LogFile + fileName + ".log";
            }
            else
            {
                LogFile = LogFile + "\\" + fileName + ".log";
            }

            try
            {
                FileStream fileStream = new FileStream(LogFile, FileMode.OpenOrCreate);
                fileStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private void writeInfos(string messagestr)
        {
            try
            {
                FileOpen();
                string text = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]";
                string value = text + "\n" + messagestr;
                sw.WriteLine(value);
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private void FileOpen()
        {
            sw = new StreamWriter(LogFile, append: true);
        }

        private void FileClose()
        {
            if (sw != null)
            {
                sw.Flush();
                sw.Close();
                sw.Dispose();
                sw = null;
            }
        }

        public void WriteLog(string msg)
        {
            if (msg != null)
            {
                writeInfos(msg.ToString());
            }
        }

        public void Dispose()
        {
        }

        public void WriteExceptionLog(Exception e)
        {
            WriteLog("Message:" + e.Message);
            WriteLog("Source:" + e.Source);
            WriteLog("InnerException:" + e.InnerException.ToString2());
            WriteLog("TargetSite:" + e.TargetSite.ToString2());
            WriteLog("StackTrace:" + e.StackTrace);
            StackTrace stackTrace = new StackTrace(e, fNeedFileInfo: true);
            WriteLog("LineNumber:" + stackTrace.GetFrame(0).GetFileLineNumber());
            WriteLog("ColumnNumber:" + stackTrace.GetFrame(0).GetFileColumnNumber());
            WriteLog("FileName:" + stackTrace.GetFrame(0).GetFileName());
        }
    }
}
